﻿using Ay.Framework.WPF;
using Ay.Framework.WPF.Controls;
using Base.BLL;
using Base.DAL;
using MPSystem;
using MPSystem.Models;
using MPSystem.Util;
using MPSystem.Views.YFQ;
using MPSystem.Views.ZCYL;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Forms;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Visifire.Charts;

namespace ADX.Views
{
    /// <summary>
    /// ZCYLPage.xaml 的交互逻辑
    /// </summary>
    public partial class ZCYLPage_test : Page
    {
        //通用类
        Common common = new Common();
        public static ZCYLPage_test Me = null;
        public static int cqbh=0,gzmbh=0;
        
        public ObservableCollection<ReportZCModel> AllDatas { get; set; } = new ObservableCollection<ReportZCModel>();
        public DataQuery_ZCAnalysisModelSearchModel SearchModel { get; set; } = new DataQuery_ZCAnalysisModelSearchModel();

        private double UpperLimit = 40;//上限值
        private double LowLimit = 20;//下限值
        private double WarnLimit = 20;//下限值
        private double gj1 = 400, gj2 = 400;//第一、第二通道缸径
        private string ComanpyName = "";
        bool FirstReflash = true;
        bool FirstLoadWarn = true;
        List<Dictionary<string, string>> conditons = new List<Dictionary<string, string>>();
        private string bh = "", dtStart = "", dtEnd = "", wz = "", channel = "",  isMPa = "", zbhs= "" , IfVisible ="是",dw="MPa";
        double minP = 0;

        private bool _IsBusy = false;
        public bool IsBusy
        {
            get { return _IsBusy; }
            set {  _IsBusy=value ; }
        }
 
        public ZCYLPage_test()
        {
            InitializeComponent();
            Loaded += AyPage_Loaded;
            Me = this;
        }
 

        void AyPage_Loaded(object sender, RoutedEventArgs e)
        {
            Loaded -= AyPage_Loaded;
            var rcq = ConfigService.GetCQ(true);
            if (rcq.Count() == 0)
            {
                AyMessageBox.ShowError("没有测区！");
                return;
            }
            combcq.ItemsSource = rcq;
            combcq.SelectedIndex = 0;
            //工作面
            var rgzm = ConfigService.GetGZM(rcq.ElementAt(0).CQBH);
            combgzm.ItemsSource = common.LoadCombox_IECobx(rgzm);
            if (rgzm.Count() > 0) combgzm.SelectedIndex = 1;

            ComanpyName = common.GetCompanyName();
            T_CompayName.Text = ComanpyName + " 综 采 监 测 报 表";
        }

        #region 更新表头
        private void UpdateHead()
        {
            var cond = ZCYLPage_testCondition.Me.Cond;
            if (combgzm.SelectedItem==null || AyCommon.ToInt(combgzm.SelectedValue) <= 0 || cond.Count == 0)
            {
                hGZM.Text = "—";
                hRZBH.Text = "—";
                hDATE.Text = "—";
                return;
            }            
            hGZM.Text = ((AyCheckBoxItemModel)combgzm.SelectedItem).ItemText;
            hRZBH.Text = cond["rzbh"];
            hDATE.Text = cond["dtStart"] + "至" + cond["dtEnd"];
        }
        #endregion

        private void LayoutRoot_load(object sender, EventArgs e)
        {
            //syncData();
        }


        void syncData()
        {
            UpdateHead();
            var cond = ZCYLPage_testCondition.Me.Cond;
            if (cond.Count == 0) return;
            BackgroundWorker worker = new BackgroundWorker();
            worker.DoWork += (o, ea) =>
            {
                //no direct interaction with the UI is allowed from this method
                AyThread.Instance.RunUI(() =>
                { 
                    dtStart = cond["dtStart"];
                    dtEnd = cond["dtEnd"];
                    zbhs = cond["zbhs"];
                    int channel= AyCommon.ToInt(cond["channel"]);
                    string rzbh= cond["rzbh"];
                    minP= AyCommon.ToDouble(cond["minP"]);
                    dw= cond["dw"];
                    bool draw = cond["draw"] == "1";
                    DataZcService ds = new DataZcService();
                   
                    string[] s = zbhs.Split(',');
                    int[] bhs = new int[s.Length];//编号列表
                    for (int b = 0; b < s.Length; b++)
                    {
                        bhs[b] = AyCommon.ToInt(s[b]);
                    }
                    DateTime db = AyCommon.ToDateTime(dtStart), de = AyCommon.ToDateTime(dtEnd);
                    //db = new DateTime(2018,12,23); de = new DateTime(2018, 12, 24);
                    cqbh = AyCommon.ToInt(combcq.SelectedValue);
                    gzmbh=AyCommon.ToInt(combgzm.SelectedValue);
                    var r = ds.Report(cqbh,gzmbh,bhs, db, de,channel, minP, dw=="MPa");
                    if (draw)  //确认是否显示曲线
                    {
                        XX.Visibility = System.Windows.Visibility.Visible;
                        XX.Height = 200;
                        CreateChartColumn("监测报表",r.DYZJBH, r.AvgZL);
                    }
                    else
                    {
                        XX.Height = 0;
                        XX.Visibility = System.Windows.Visibility.Collapsed;
                    }
                    zm_zd.Text = r.WHOLE[0].ToString("N"); zm_zx.Text = r.WHOLE[1].ToString("N"); zm_pj.Text = r.WHOLE[2].ToString("N");//整面
                    sm_zd.Text = r.TOP[0].ToString("N"); sm_zx.Text = r.TOP[1].ToString("N"); sm_pj.Text = r.TOP[2].ToString("N");//上面
                    mm_zd.Text = r.MID[0].ToString("N"); mm_zx.Text = r.MID[1].ToString("N"); mm_pj.Text = r.MID[2].ToString("N");//中面
                    xm_zd.Text = r.BOTTOM[0].ToString("N"); xm_zx.Text = r.BOTTOM[1].ToString("N"); xm_pj.Text = r.BOTTOM[2].ToString("N");//下面
                    hgl.Text = string.Format("{0:N}%",r.PoP*100);//合格率
                    LoadTableData(r);

                });
                //CreateChartColumn("测试", strListx, strListy);
            };
            worker.RunWorkerCompleted += (o, ea) =>
            {
                //work has completed. you can now interact with the UI
                busyin1.IsBusy = false;
            };
            //set the IsBusy before you start the thread
            busyin1.IsBusy = true;
            worker.RunWorkerAsync();
        }

        private void btnquery_Click(object sender, RoutedEventArgs e)
        {
            if (combgzm.SelectedIndex == -1 || combgzm.SelectedValue.ToString() == "-1")
            {
                AyMessageBox.ShowError("请先选择测区和工作面！");
                return;
            }
            gzmbh = int.Parse(combgzm.SelectedValue.ToObjectString());
            ZCYLPage_testCondition.Me.LoadBH();
            syncData();
        }

        private void btnHquery_Click(object sender, RoutedEventArgs e)
        {
            if (combgzm.SelectedIndex == -1 || combgzm.SelectedValue.ToString() == "-1")
            {
                AyMessageBox.ShowError("请先选择测区和工作面！");
                return;
            }
            gzmbh = int.Parse(combgzm.SelectedValue.ToObjectString());
            ShowNavigationWindow("多条件筛选", "/Views/YFQ/ZCYLPage_testCondition.xaml", 600, 500);
        }

        private void btnprint_Click(object sender, RoutedEventArgs e)
        {
            //System.Windows.Controls.PrintDialog dialog = new System.Windows.Controls.PrintDialog();
            //if (dialog.ShowDialog() == true)
            //{
            //    gbox.Visibility= System.Windows.Visibility.Collapsed; 
            //    dialog.PrintVisual(printArea, "综采监测报表");
            //    gbox.Visibility = System.Windows.Visibility.Visible;
            //}
            
            SaveFileDialog saveDialog = new SaveFileDialog();
            saveDialog.DefaultExt = "xls";
            saveDialog.Filter = "Excel文件|*.xls";
            saveDialog.FileName = "综采数据报表导出";
            if (saveDialog.ShowDialog() != DialogResult.OK)
            {
                return;
            }
            string saveFileName = saveDialog.FileName;
            if (!ExcelHelper.FileEditable(saveFileName))
            {
                AyMessageBox.ShowError("文件被占用，请关闭文件" + saveFileName);
                return;
            }
            
            var cond = ZCYLPage_testCondition.Me.Cond;
            if (cond.Count == 0) return;
            dtStart = cond["dtStart"];
            dtEnd = cond["dtEnd"];
            zbhs = cond["zbhs"];
            int channel = AyCommon.ToInt(cond["channel"]);
            string rzbh = cond["rzbh"];
            minP = AyCommon.ToDouble(cond["minP"]);
            dw = cond["dw"];
            bool draw = cond["draw"] == "1";
            string[] s = zbhs.Split(',');
            int[] bhs = new int[s.Length];//编号列表
            for (int b = 0; b < s.Length; b++)
            {
                bhs[b] = AyCommon.ToInt(s[b]);
            }

            DataZcService.ExportParam param = new DataZcService.ExportParam();
            param.ComanpyName = T_CompayName.Text;
            param.DW = dw;//单位
            param.GZM = combgzm.Text;//工作面名称
            param.RZBH = rzbh;//认证编号
            param.WithChart = draw;//是否生成曲线
            param.HGZ = dw == "MPa" ? minP : 3.14 * (gj1 * gj1 + gj2 * gj2) / 4 / 1000 * minP; ;//合格值
            param.UpperLimit = dw == "MPa" ? UpperLimit : 3.14 * (gj1 * gj1 + gj2 * gj2) / 4 / 1000 * UpperLimit;//上限值
            param.WarnLimit = dw == "MPa" ? WarnLimit : 3.14 * (gj1 * gj1 + gj2 * gj2) / 4 / 1000 * WarnLimit; ;//报警值
            param.Sign = cond["sign"];

            DataZcService ds = new DataZcService();
            DateTime db = AyCommon.ToDateTime(dtStart);
            DateTime de = AyCommon.ToDateTime(dtEnd);
            //db = new DateTime(2018, 12, 20); de = new DateTime(2018, 12, 30);
            //AyThread.Instance.RunNew(() =>
            //{
                ds.ExportReport(saveFileName, param, cqbh, gzmbh, bhs, db, de);
                AyMessageBox.ShowInformation("已导出至" + saveFileName);
            //});
        }



        /// <summary>/// 弹出层对象/// </summary>

        public static NavigationWindow window = null;
        /// <summary>/// 使用NavigationWindow弹出页面/// </summary>

        private void ShowNavigationWindow(string title, string uri, int width, int height)
        {
            if (window == null)
            {
                window = new NavigationWindow();
                window.Title = title;
                window.Width = width;
                window.Height = height;
                window.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                window.ResizeMode = ResizeMode.NoResize;
                window.Source = new Uri(uri, UriKind.Relative);
                window.ShowsNavigationUI = false;
                window.Closing += Window_Closing;
                // window.pas += new window.PassValuesHandler(ReceiveValues);
            }
            else
            {
                ZCYLPage_testCondition.Me.LoadBH();
            }
            window.ShowDialog();
        }

        private void Window_Closing(object sender, CancelEventArgs e)
        {
            ZCYLPage_testCondition.Me.UpdateCond();
            window.Hide();
            Me.syncData();
            e.Cancel = true;
        }

        /// <summary>/// 关闭弹出层/// </summary>
        private void CloseNavigationWindow(){
            window.Close();
        }


        public void CreateChartColumn(string name, List<string> valuex,List<double> valuey)
        {
            chart.Series.Clear();
            chart.TrendLines.Clear();
            if (FirstReflash)
            {
                chart.ToolBarEnabled = false;
                //设置图标的属性
                chart.ScrollingEnabled = false;//是否启用或禁用滚动
                chart.View3D = false;//3D效果显示
                //创建一个标题的对象
                Title title = new Title();
                //设置标题的名称
                title.Text = Name;
                title.Padding = new Thickness(0, 10, 5, 0);
                //向图标添加标题
                chart.Titles.Add(title);
                FirstReflash = false;
            }
            chart.AxesY.Clear();
            Axis yAxis = new Axis();
            //设置图标中Y轴的最小值永远为0           
            yAxis.AxisMinimum = 0;
            yAxis.AxisMaximum = dw=="MPa"?60:15000;
            //设置图表中Y轴的后缀          
            yAxis.Suffix = "";
            chart.AxesY.Add(yAxis);

            //创建第一个DataSeries
            DataSeries oneDataSeries = new DataSeries();
            oneDataSeries.LabelEnabled = true;
            oneDataSeries.LabelText = "#YValue";
            oneDataSeries.LegendText = "平均阻力";
            oneDataSeries.RenderAs = RenderAs.Line;
            oneDataSeries.Color = new SolidColorBrush(Colors.LightGreen);
            //创建第一个DataSeries的DataPoint
            DataPoint oneDataPoint = null;
            for (int i = 0; i < valuex.Count; i++)
            {
                oneDataPoint = new DataPoint();
                oneDataPoint.AxisXLabel = valuex[i];
                oneDataPoint.YValue = valuey[i];
                oneDataSeries.DataPoints.Add(oneDataPoint);
            }
            chart.Series.Add(oneDataSeries);

            
            TrendLine tl = new TrendLine();
            tl.Value = dw == "MPa"?minP:3.14*(gj1*gj1+gj2*gj2)/4/1000*minP;
            tl.LineThickness = 1;
            tl.LabelText = "合格值";
            tl.LineColor = new SolidColorBrush(Colors.LightPink);
            chart.TrendLines.Add(tl);

            TrendLine t2 = new TrendLine();
            t2.Value = dw == "MPa" ? UpperLimit : 3.14 * (gj1 * gj1 + gj2 * gj2) /4 / 1000 * UpperLimit; 
            t2.LineThickness = 1;
            t2.LabelText = "上限值";
            t2.LineColor = new SolidColorBrush(Colors.LightBlue);
            chart.TrendLines.Add(t2);


            TrendLine t3 = new TrendLine();
            t3.Value = dw == "MPa" ? WarnLimit : 3.14 * (gj1 * gj1 + gj2 * gj2) / 4 / 1000 * WarnLimit;
            t3.LineThickness = 1;
            t3.LabelText = "报警值";
            t3.LineColor = new SolidColorBrush(Colors.LightGreen);
            chart.TrendLines.Add(t3);
            FirstReflash = false;
        }

        void LoadTableData(ReportZc rt)
        {
            if (rt == null) return;
            AllDatas.Clear();
            for (int i = 0; i < rt.YLFZBH.Count; i++)
            {
                ReportZCModel cc = new ReportZCModel();
                cc.FZBH = rt.YLFZBH[i];
                cc.ZJBH = rt.DYZJBH[i];
                cc.AZWZ = rt.WZ[i];
                cc.ZlMax = rt.MaxZL[i];
                cc.ZlAvg = rt.AvgZL[i];
                cc.CCLMin = rt.MinCCL[i];
                cc.CCLAvg = rt.AvgCCL[i];
                cc.MZLMax = rt.MaxMZL[i];
                cc.MZLAvg = rt.AvgMZL[i];
                AllDatas.Add(cc);
            }
            if (AllDatas.Count > 0)
            {
                tableView.ItemsSource = AllDatas;
            }
           
        }

        private void combcq_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (combcq.SelectedValue == null) return;
            cqbh = AyCommon.ToInt(combcq.SelectedValue);
            var gzmSource = ConfigService.GetGZM(cqbh);
            combgzm.ItemsSource = common.LoadCombox_IECobx(gzmSource);
            if (gzmSource.Count() > 0) combgzm.SelectedIndex = 1;
        }

        private void Combgzm_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            gzmbh = AyCommon.ToInt(combgzm.SelectedValue);
            UpdateHead();
            if (combgzm.SelectedValue == null) return;
            View_ZC_INI_CS cs = ConfigService.FindZc(cqbh, gzmbh);
            if (cs != null)
            {
                UpperLimit = cs.YLSX;
                LowLimit = cs.YLXX;
                WarnLimit = cs.YLBJZ;
                gj1 = cs.FIRSTGJ;
                gj2 = cs.SECONDGJ;
                FirstLoadWarn = true;
            }
        }
    }
}
